package com.example.serialization;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.omg.CORBA.PUBLIC_MEMBER;

import java.io.*;

/**
 * @ClassName SerializationTest
 * @Description TODO
 * @Author: XMK
 * @Date: 2020/9/30 9:17
 * @Version: 1.0
 */
public class SerializationTest {

    @Test
    public void serial() throws IOException {
        Car car = new Car();
        car.setName("aa");
        car.setType("qq");

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d://aalog/ocs/car.txt"));
        oos.writeObject(car);
    }

    @Test
    public void serailMem() throws IOException, ClassNotFoundException {
        Car car = new Car();
        car.setName("aa");
        car.setType("qq");

        ByteArrayOutputStream byteArrOutput = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(byteArrOutput);
        oos.writeObject(car);
        System.out.println(car);

        System.out.println(byteArrOutput.size());
        System.out.println(byteArrOutput.toByteArray().length);


        ByteArrayInputStream byteArrInput = new ByteArrayInputStream(byteArrOutput.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(byteArrInput);
        Object o = ois.readObject();

        System.out.println(o);
        System.out.println((Car)o);

    }

    @Test
    public void serialFastJSON() {
        Car car = new Car();
        car.setName("aa");
        car.setType("qq");

        byte[] bytes = JSON.toJSONBytes(car);

        System.out.println(bytes.length);

        Car a = JSON.parseObject(bytes, Car.class);
        System.out.println(a);

    }

    @Test
    public void serialJackson() throws IOException {
        Car car = new Car();
        car.setName("aa");
        car.setType("qq");

        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = objectMapper.writeValueAsBytes(car);

        System.out.println(bytes.length);

        Car car1 = objectMapper.readValue(bytes, Car.class);

        System.out.println(car1);
    }

    @Test
    public void deserial() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d://aalog/ocs/car.txt"));
        Object o = ois.readObject();
        System.out.println(o);

        Car car = (Car) o;
        System.out.println(car);

    }
}
